<?php
//(c) Copyright 2016 wonyun. All Rights Reserved.
/**
 *
 * 订单相关模块
 * author：Rogermmg
 **/
class CountAction extends Action {
	public function _initialize() {
		$action = array('users' => array(), 'anonymous' => array(''));
		B('Authenticate', $action);
	}

	public function index() {
		$this -> alert = parseAlert();
		$this -> display();
	}

	public function li() {
		$d_mongo = D("Mongo");

		$where['t_start'] = $this -> _get('t_start', 'trim', '');
		$where['t_end'] = $this -> _get('t_end', 'trim', '');
		$where['teamid'] = json_decode($this -> _get('teamid', 'trim', ''), TRUE);

		//条件20 < i <= 30  array( "i" => array( "\$gt" => 20, "\$lte" => 30 ) );
		//$lwhere = $this -> _get('where', 'intval', '');
		$sort = array("city" => 1, "ordered" => -1);
		$p = $this -> _get('p', 'intval', 1);
		

		if ($where['t_start']) {
			//选择时间区间
			$teamtime=array(
				't_start'=>$where['t_start'],
				't_end'=>$where['t_end']
			);
			$status = $where;
			$status['teamid']=urlencode(json_encode($where['teamid']));
			
			//改变数组中字符串为整形
			foreach($where['teamid'] as $tid){
				$teamid[]=(int)$tid;
			}
			
			if (!$where['teamid']) {
				unset($status['teamid']);
				$lwhere = array("docid" => array("\$gt" => strtotime($where['t_start']), "\$lte" => strtotime($where['t_end'])));
			} else {
				$lwhere = array("docid" => array("\$gt" => strtotime($where['t_start']), "\$lte" => strtotime($where['t_end'])), "teamid" => array('$in'=>array_values($teamid)));
			}
		}else{
			$lwhere = '';
		}

//		dump($lwhere);
		$olist = $d_mongo -> Pagefind($lwhere, $p, $status, $sort, 50,'puser');
		//		dump($olist);exit();
		
		//合并数据
		/*foreach($olist['userlist'] as $kes=>$vess){
			$lwhere['psid']=$vess['psid'];
			$conlist[$kes]=$this->merge($vess,$lwhere);
		}*/
//		dump($lwhere);


		$teamset = M("teamset") -> select();
		
		if($where['teamid']){
			foreach($where['teamid'] as $ke=>$vos){
				$sne[$ke]= M("teamset")->where(array("teamid"=>$vos))->find();
				$tname[$ke]=$sne[$ke]['teamname'];
			}
			$this -> assign('teamname', $tname);
		}
		
		$this -> assign('teamtime', $teamtime);
		$this -> assign('teamid', $teamid);
		$this -> assign('teamset', $teamset);
		$this -> assign('status', $status);
		$this -> assign('page', $olist['page']);
//		$this -> assign('olist', $conlist);
		$this -> assign('olist', $olist['userlist']);
		$this -> alert = parseAlert();
		$this -> display();
	}

	//日常单添加
	public function add() {
		$d_mongo = D("Mongo");
		$this -> alert = parseAlert();
		$this -> display();
	}

	//团队ID添加
	public function teamset() {
		$m = M('teamset');
		if ($this -> isPost()) {
			foreach ($_POST['teamname'] as $k => $temaname) {
				if ($temaname) {
					$team['teamid'] = $_POST['teamid'][$k];
					$team['teamname'] = $temaname;

					$ose = $m -> where(array("setid" => $_POST['setid'][$k])) -> find();
					if (!$ose) {
						$m -> data($team) -> add();
					} else {
						$m -> where(array("setid" => $_POST['setid'][$k])) -> save($team);
					}
				}
			}
			alert('success', '操作成功！', U('chrm/count/teamset'));
		} else {
			$teamset = $m -> select();
			$this -> assign('setlist', $teamset);
			$this -> alert = parseAlert();
			$this -> display();
		}
	}

	public function upload() {
		if ($this -> isPost()) {
			$m_mongo = M('mongo');
			$d_mongo = D("Mongo");
			$times=time();
			
			if (isset($_FILES['excel']['size']) && $_FILES['excel']['size'] != null) {
				import('@.ORG.UploadFile');
				$upload = new UploadFile();
				$upload -> maxSize = 20000000;
				$upload -> allowExts = array('xls', 'xlsx');
				$dirname = './Uploads/excel/' . date('Ym', time()) . '/' . date('d', time()) . '/';
				if (!is_dir($dirname) && !mkdir($dirname, 0777, true)) {
					alert('error', '附件上传目录不可写', U('chrm/count/add'));
				}
				$upload -> savePath = $dirname;
				if (!$upload -> upload()) {
					alert('error', $upload -> getErrorMsg(), U('chrm/count/add'));
				} else {
					$info = $upload -> getUploadFileInfo();
				}
			}
//						dump($_FILES);exit();
			if (is_array($info[0]) && !empty($info[0])) {
				$savePath = $dirname . $info[0]['savename'];
			} else {
				alert('error', '上传失败', U('chrm/count/add'));
			}
			import("ORG.PHPExcel.PHPExcel");
			$PHPExcel = new PHPExcel();
			$PHPReader = new PHPExcel_Reader_Excel2007();
			if (!$PHPReader -> canRead($savePath)) {
				$PHPReader = new PHPExcel_Reader_Excel5();
			}
			$PHPExcel = $PHPReader -> load($savePath);
			$currentSheet = $PHPExcel -> getSheet(0);
			$allRow = $currentSheet -> getHighestRow();
			if ($allRow <= 1) {
				alert('error', '上传文件无有效数据', U('chrm/count/add'));
			} else {

				for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
					
					$psid=$currentSheet -> getCell('C' . $currentRow) -> getValue();
					$psname=$currentSheet -> getCell('B' . $currentRow) -> getValue();
					$teamid=$currentSheet -> getCell('G' . $currentRow) -> getValue();
					
					/*设置日期转为ID*/
					$Docid = strtotime($currentSheet -> getCell('A' . $currentRow) -> getValue());
					
					//有效单
					$valid = $currentSheet -> getCell('L' . $currentRow) -> getValue();
					//40分内送达
					$ih40min = $currentSheet -> getCell('M' . $currentRow) -> getValue();

					//40分送达率
					$m40 = (int)$ih40min / (int)$valid;
					$data = array(
					"wid"=>$times,
					"docid" => $Docid, 
					"adddate" => $currentSheet -> getCell('A' . $currentRow) -> getValue(), 
					"psname" => $psname, 
					"psid" => $psid, 
					"city" => $currentSheet -> getCell('D' . $currentRow) -> getValue(), 
					"teamname" => $currentSheet -> getCell('H' . $currentRow) -> getValue(), 
					"teamid" => $teamid, 
					"ordered" => $currentSheet -> getCell('K' . $currentRow) -> getValue(), 
					"valid" => $currentSheet -> getCell('L' . $currentRow) -> getValue(), 
					"40min" => $currentSheet -> getCell('M' . $currentRow) -> getValue(), 
					"40_60min" => $currentSheet -> getCell('N' . $currentRow) -> getValue(), 
					"timeout" => $currentSheet -> getCell('O' . $currentRow) -> getValue(), 
					"40points" => $m40, 
					"unusual" => $currentSheet -> getCell('S' . $currentRow) -> getValue(), 
					"bad_review" => $currentSheet -> getCell('T' . $currentRow) -> getValue(), 
					"mid_review" => $currentSheet -> getCell('U' . $currentRow) -> getValue(), 
					"good_review" => $currentSheet -> getCell('V' . $currentRow) -> getValue(), 
					"com_volume" => $currentSheet -> getCell('W' . $currentRow) -> getValue(), 
					"com_sended" => $currentSheet -> getCell('X' . $currentRow) -> getValue(), 
					"com_badservice" => $currentSheet -> getCell('Y' . $currentRow) -> getValue(), 
					"com_business" => $currentSheet -> getCell('Z' . $currentRow) -> getValue());
					//					$create_time = intval(PHPExcel_Shared_Date::ExcelToPHP($time_info)) - 8 * 60 * 60;
					//					$data['create_time'] = $create_time;
					//					$data['from_ip'] = get_client_ip();
					
					if(!$data["docid"]){
						alert('error', '上传文件数据日期格式不正确！', U('chrm/count/add'));
					}
					$adddata = $d_mongo -> add($data);
					
					$udata=array(
						'psid'=>$psid,
						'psname'=>$psname,
						'teamid'=>$teamid
					);
					$this->puser($udata,'puser');//更新配送员
					
					$teamd=array(
						"teamid"=>$teamid,
						"teamname"=>$data['teamname']
					);
					$this->teamup($teamd);

					if (!$adddata) {
						alert('error', '出错=》' . $adddata, U('chrm/count/add'));
						break;
					}
				}
				$m_mongos = array();
				$m_mongos['type']='user';
				$m_mongos['oldname']=$_FILES['excel']["name"];
				$m_mongos['filename'] = $info[0]['savename'];
				$m_mongos['fileid'] = $Docid;
				$m_mongos['wid']=$times;
				$m_mongos['user_id'] = $_SESSION['user_id'];
				$m_mongos['update'] = time();
				if (!$m_mongo -> data($m_mongos) -> add()) {
					alert('error', '出错=》MYSQL写入失败', U('chrm/count/add'));
				}
				alert('success', '导入成功！', U('chrm/count/index'));
			}
		} else {
			$this -> display();
		}
	}

	//团队导入
	public function team(){
		if ($this -> isPost()) {
			$m_mongo = M('mongo');
			$d_mongo = D("Mongo");
			$times=time();
			if (isset($_FILES['excel']['size']) && $_FILES['excel']['size'] != null) {
				import('@.ORG.UploadFile');
				$upload = new UploadFile();
				$upload -> maxSize = 20000000;
				$upload -> allowExts = array('xls', 'xlsx');
				$dirname = './Uploads/excel/' . date('Ym', time()) . '/' . date('d', time()) . '/';
				if (!is_dir($dirname) && !mkdir($dirname, 0777, true)) {
					alert('error', '附件上传目录不可写', U('chrm/count/add'));
				}
				$upload -> savePath = $dirname;
				if (!$upload -> upload()) {
					alert('error', $upload -> getErrorMsg(), U('chrm/count/add'));
				} else {
					$info = $upload -> getUploadFileInfo();
				}
			}
			//			dump($_FILES);exit();
			if (is_array($info[0]) && !empty($info[0])) {
				$savePath = $dirname . $info[0]['savename'];
			} else {
				alert('error', '上传失败', U('chrm/count/add'));
			}
			import("ORG.PHPExcel.PHPExcel");
			$PHPExcel = new PHPExcel();
			$PHPReader = new PHPExcel_Reader_Excel2007();
			if (!$PHPReader -> canRead($savePath)) {
				$PHPReader = new PHPExcel_Reader_Excel5();
			}
			$PHPExcel = $PHPReader -> load($savePath);
			$currentSheet = $PHPExcel -> getSheet(0);
			$allRow = $currentSheet -> getHighestRow();
			if ($allRow <= 1) {
				alert('error', '上传文件无有效数据', U('chrm/count/li'));
			} else {

				for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
					
					$adddate=$currentSheet -> getCell('A' . $currentRow) -> getValue();
					
					//$Docid=intval(PHPExcel_Shared_Date::ExcelToPHP($psid));
					$Docid=intval(($adddate - 25569) * 3600 * 24);
					$psid=date("Y-m-d",$Docid);
					$c_ac=$currentSheet -> getCell('AF' . $currentRow) -> getValue();
					$c_ad=$currentSheet -> getCell('AG' . $currentRow) -> getValue();
					$c_ak=$currentSheet -> getCell('AN' . $currentRow) -> getValue();
					$c_o=$currentSheet -> getCell('O' . $currentRow) -> getValue();
					$c_q=$currentSheet -> getCell('Q' . $currentRow) -> getValue();
					$c_y=$currentSheet -> getCell('Y' . $currentRow) -> getValue();
					$c_t=$currentSheet -> getCell('T' . $currentRow) -> getValue();
					$c_p=$currentSheet -> getCell('P' . $currentRow) -> getValue();
					$c_r=$currentSheet -> getCell('R' . $currentRow) -> getValue();
					$p_yc=(int)$c_ac/((int)$c_o-(int)$c_q);
					$p_40min=(int)$c_y/(int)$c_t;
					$p_cs=(int)$c_ad/(int)$c_r;
					$p_ts=(int)$c_ak/((int)$c_p-(int)$c_q);		
					
					$data=array(
						"wid"=>$times,
						"docid"=>$Docid,
						"adddate"=>$psid,
						"city"=>$currentSheet -> getCell('C' . $currentRow) -> getValue(),
						"teamid"=>$currentSheet -> getCell('F' . $currentRow) -> getValue(),
						"teamname"=>$currentSheet -> getCell('G' . $currentRow) -> getValue(),
						"tuidan"=>$currentSheet -> getCell('K' . $currentRow) -> getValue(),
						"zhudong"=>$currentSheet -> getCell('N' . $currentRow) -> getValue(),
						"teamjie"=>$c_o,
						"peisonged"=>$c_p,
						"qizha"=>$c_q,
						"ordered"=>$c_r,
						"js_order"=>$c_t,
						"bad_com"=>$currentSheet -> getCell('U' . $currentRow) -> getValue(),
						"mid_com"=>$currentSheet -> getCell('V' . $currentRow) -> getValue(),
						"good_com"=>$currentSheet -> getCell('W' . $currentRow) -> getValue(),
						"40min"=>$c_y,
						"yc_order"=>$c_ac,
						"caoshi"=>$c_ad,
						"dd_caoshi"=>$currentSheet -> getCell('AH' . $currentRow) -> getValue(),
						"toushu"=>$c_ak,
						"p_yc"=>$p_yc,
						"p_40min"=>$p_40min,
						"p_cs"=>$p_cs,
						"p_ts"=>$p_ts
					);
					
					if(!$data["docid"]){
						alert('error', '上传文件数据格式不正确！', U('chrm/count/li'));
					}
					$adddata = $d_mongo -> add($data,'team');

					$teamd=array(
						"teamid"=>$data['teamid'],
						"teamname"=>$data['teamname']
					);
					$this->teamup($teamd);
					$this->puser($teamd,'teamname');//更新团队
					
					if (!$adddata) {
						alert('error', '出错=》' . $adddata, U('chrm/count/li'));
						break;
					}
				}
				$m_mongos = array();
				$m_mongos['type']='team';
				$m_mongos['oldname']=$_FILES['excel']["name"];
				$m_mongos['filename'] = $info[0]['savename'];
				$m_mongos['fileid'] = $Docid;
				$m_mongos['wid']=$times;
				$m_mongos['user_id'] = $_SESSION['user_id'];
				$m_mongos['update'] = time();
				if (!$m_mongo -> data($m_mongos) -> add()) {
					alert('error', '出错=》MYSQL写入失败', U('chrm/count/li'));
				}
				alert('success', '导入成功！', U('chrm/count/index'));
			}
		}else{
			$this -> alert = parseAlert();
			$this -> display();
		}
		
	}

	//列出团队数据
	public function liteam(){
		$d_mongo = D("Mongo");

		$where['t_start'] = $this -> _get('t_start', 'trim', '');
		$where['t_end'] = $this -> _get('t_end', 'trim', '');
		$where['teamid'] = json_decode($this -> _get('teamid', 'trim', ''), TRUE);
		
		$sort = array("city" => 1, "ordered" => -1);
		$p = $this -> _get('p', 'intval', 1);

		if ($where['t_start']) {
			//选择时间区间
			$teamtime=array(
				't_start'=>$where['t_start'],
				't_end'=>$where['t_end']
			);
			$status = $where;
			$status['teamid']=urlencode(json_encode($where['teamid']));
			
			//改变数组中字符串为整形
			foreach($where['teamid'] as $tid){
				$teamid[]=(int)$tid;
			}
			
			if (!$where['teamid']) {
				unset($status['teamid']);
				$lwhere = array("docid" => array('$gt' => strtotime($where['t_start']), '$lte' => strtotime($where['t_end'])));
			} else {
				$lwhere = array("docid" => array('$gt' => strtotime($where['t_start']), '$lte' => strtotime($where['t_end'])), "teamid" => array('$in'=>array_values($teamid)));
			}
		}else{
			$lwhere = '';
		}

		$teamset = M("teamset") -> select();
		
		$olist = $d_mongo -> Pagefind($lwhere, $p, $status, $sort, 60,'teamname');
		
		if($where['teamid']){
			foreach($where['teamid'] as $ke=>$vos){
				$sne[$ke]= M("teamset")->where(array("teamid"=>$vos))->find();
				$tname[$ke]=$sne[$ke]['teamname'];
			}
			$this -> assign('teamname', $tname);
		}
		
		
		
		$this -> assign('teamtime', $teamtime);
		$this -> assign('teamid', $teamid);
		$this -> assign('teamset', $teamset);
		$this -> assign('status', $status);
		$this -> assign('page', $olist['page']);
		$this -> assign('olist', $olist['userlist']);
		$this -> alert = parseAlert();
		$this -> display();
	}
	
	public function teamone(){
		if($_GET['tid']){
			$d_mongo = D("Mongo");
			$where['t_start'] = $this -> _get('t_start', 'trim', '');
			$where['t_end'] = $this -> _get('t_end', 'trim', '');
			$where['teamid'] = $_GET['tid'];
			$sort = array("city" => 1);
			$p = $this -> _get('p', 'intval', 1);
			
			if ($where['t_start']) {
				//选择时间区间
				$teamtime=array(
					't_start'=>$where['t_start'],
					't_end'=>$where['t_end']
				);
				$status = $where;
				$status['teamid']=$where['teamid'];
				
				$lwhere = array("docid" => array('$gt' => strtotime($where['t_start']), '$lte' => strtotime($where['t_end'])), "teamid" =>$where['teamid'] );
			}else{
				$lwhere['teamid'] = $_GET['tid'];
			}
			
			$teamset = M("teamset") ->where(array("setid"=>$_GET['tid']))-> find();
			
			$olist = $d_mongo -> Pagefind($lwhere, $p, $status, $sort, 60,'teamname');
//			dump($p);exit;
			$this -> assign('teamname', $teamset['teamname']);
			$this -> assign('status', $status);
			$this -> assign('page', $olist['page']);
			$this -> assign('olist', $olist['userlist']);
			$this -> alert = parseAlert();
			$this -> display();
		}else{
			alert('error', '查询的内容不存在', U('chrm/count/liteam'));
		}
		
	}

	//导入文件管理
	public function files(){
		$f=D('Count');
		$p = $this -> _get('p', 'intval', 0);
		$wid=$this -> _get('wid', 'intval', '');
		$type=$this -> _get('type', 'trim', '');
		
		if($wid!=''){
			$d_mongo=D("Mongo");
			$where['wid']=$wid;
			
			switch($type){
				case "user":
					$collection='dayorder';
					break;
				case "team":
					$collection='team';
					break;
				case "order":
					$collection='delivery_detail';
					break;
			}
			
			
			$remove=$d_mongo->remove($where,$collection);
			if(!$remove){
				alert('error', '操作删除数据失败！', U('chrm/count/files'));
			}else{
				$f->upmogo($wid);
				alert('success', '操作成功！', U('chrm/count/files'));
			}
		}
		
		$limit=15;
		
		$lifile=$f->mfile($p,$limit);
//		dump($lifile);
		$this -> assign('page', $lifile['page']);
		$this -> assign('olist', $lifile['list']);
		$this -> alert = parseAlert();
		$this -> display();
	}

	//更新配送员信息Mongo
	function puser($data,$table){
		$m_db=D("Mongo");
		if(!$data['teamid']){
			$u_find=$m_db->_find(array("psid"=>$data['psid']),$table);
		}else{
			$u_find=$m_db->_find(array("teamid"=>$data['teamid']),$table);
		}
		
		
		if(!$u_find){
			$m_db->add($data,$table);
		}
	}
	
	//更新团队名称
	function teamup($teamd){
		$m_mongo = M('mongo');
		$fis=$m_mongo->where(array("teamid"=>$teamd['teamid']))->find();
		if(!$fis){
			$m_mongo->data($teamd)->add();
		}
	}


}
?>